// index.js
const appData = getApp()

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
import { getHomeList, getAddressList, getHomePicList } from '../../apis/index'
Page({
  data: {
    activeAddressIndex:null,
    activeAddressName:'',
    navBarHeight: 0,
    menuRight:0,
    menuTop:0,
    menuHeight:0,
    defaultData: {
      title: "我的主页", // 导航栏标题
    },
    searchVal:"",
    index: 0,
    filterActive: 999,
    firstTabActive:false,
    array: ['美国', '中国', '巴西', '日本'],
    region: ['广东省', '广州市', '海珠区'],
    customItem: '全部',
    autoplay: true,
    imageItemVOList: [],
    listParams:{},
    filterTabs: [
      {
        label: "品牌",
        value: "2",
        key: 'name',
        data: [
          {
            value: '999',
            name: '所有'
          },
          {
            value: '科越',
            name: '科越'
          },
          {
            value: '杰艺',
            name: '杰艺'
          }
        ]
      },
      {
        label: "价格",
        value: "3",
        data: [
          {
            value: '999',
            name: '不限'
          },
          {
            value: '1',
            name: '1万以下'
          },
          {
            value: '2',
            name: '1万 - 5万'
          },
          {
            value: '3',
            name: '5万 - 20万'
          },
          {
            value: '4',
            name: '20万以上'
          }
        ]
      },
      {
        label: "类型",
        value: "5",
        data:[
          {
            value: '999',
            name: '所有'
          },
          {
            name: "纯点胶",
            value: 1,
          },
          {
            name: "点画一体",
            value: 2,
          },
          {
            name: "果冻系列",
            value: 3,
          },
          {
            name: "视觉",
            value: 4,
          },
          {
            name: "非视觉",
            value: 5,
          },
          {
            name: "配套",
            value: 6,
          },
        ]
      },
      {
        label: "排序",
        value: "4",
        data: [
          {
            value: '999',
            name: '默认排序'
          },
          {
            value: '1',
            name: '价格最高'
          },
          {
            value: '2',
            name: '价格最低'
          }
        ]
      },
    ],
    addressItemVOS: [],
    multiIndex: [0, 0, 0],
    multiArray: [],
    cityName:"",
    shopList: [
      {
        // url: '/images/1295E_main.jpeg',
        type: 1,
        name: '科越高速点胶机',
        date: '2025-06-05'
      },
      {
        // url: '/images/1698L_main.jpeg',
        type: 11,
        name: '科越双头AB双组份果冻胶机',
        date: '2025-06-06'
      },
      {
        // url: '/images/329SM_main.jpeg',
        type: 111,
        name: '科越智能背扣机',
        date: '2025-06-07'
      }
    ]
  },
  async onLoad() {
    console.log(appData.globalData.navBarHeight);
    const systemInfo = wx.getWindowInfo();
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    console.log('systemInfo', systemInfo);
    this.setData({
      navBarHeight:systemInfo.statusBarHeight + 44,
      menuRight: systemInfo.screenWidth - menuButtonInfo.right,
      menuTop:  menuButtonInfo.top,
      menuHeight : menuButtonInfo.height
    })
    this.getHomePic()
    this.getList()
    const addressItemVOS = await getAddressList()
    console.log('address list', addressItemVOS);
    console.log('ssss', appData.globalData.currentAddress);
    // multiIndex
    // addressItemVOS
    let multiIndex = [0, 0, 0]
    let getState = false
    let cityName = ''
    if (Array.isArray(addressItemVOS) && addressItemVOS.length) {
      // addressItemVOS.forEach((provinceItem, provinceIndex) => {
      //   if (Array.isArray(provinceItem.itemVOS) && provinceItem.itemVOS.length && !getState) {
      //     provinceItem.itemVOS.some((cityItem, cityIndex) => {
      //       if (cityItem.name.indexOf(appData.globalData.currentAddress) > -1) {
      //         multiIndex = [provinceIndex, cityIndex, 0]
      //         getState = true
      //         cityName = cityItem.name
      //       }
      //     })
      //   }
      // })
    }
    console.log(multiIndex, cityName);
    this.setData({
      addressItemVOS:[
        {
          addressName:"全国",
          id:99998888
        },
        ...addressItemVOS,
      ],
      // multiArray: this.processFilter(addressItemVOS, multiIndex[0], multiIndex[1]),
      multiIndex,
      cityName,
      firstTabActive:cityName?true:false
    })
  },
  async getHomePic(){
    const res = await getHomePicList({})
    console.log('res',res);
    const { imageItemVOList } = res;
    this.setData({
      imageItemVOList
    })
  },
  getDistrict(){
    // this.data.multiIndex
    console.log(123);
    const index0 = this.data.multiIndex[0]
    const index1 = this.data.multiIndex[1]
    const index2 = this.data.multiIndex[2]
    return this.data.addressItemVOS[index0].itemVOS[index1].itemVOS[index2].name
  },
  // Province, city, district
  processFilter(addressItemVOS, provinceIndex, cityIndex, districtIndex) {
    let processArray = []
    if (Array.isArray(addressItemVOS) && addressItemVOS.length) {
      const item0 = addressItemVOS[provinceIndex]
      console.log(item0);
      console.log(item0.itemVOS[cityIndex]);
      processArray = [
        addressItemVOS.map(item => {
          return item.name
        }),
        item0?.itemVOS.map(item => {
          return item.name
        }),
        item0?.itemVOS[cityIndex]?.itemVOS.map(item => {
          return item.name
        }),
      ]
    }
    return processArray
  },
  async getList(options = {}) {
    const res = await getHomeList({
      page: 1,
      pageSize: 200,
      ...options
    })
    const { records } = res;
    this.setData({
      shopList: records
    })
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  goToDetail(e) {
    wx.navigateTo({
      url: `/pages/detail/index?id=${e.currentTarget.dataset.id}`
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },

  bindRegionChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    // this.setData({
    //   region: e.detail.value
    // })
  },
  preview(e) {
    const { detail, target, currentTarget } = e
    const { index } = currentTarget.dataset
    console.log(index);
    wx.previewImage({
      current: this.data.imageItemVOList[index].url, // 当前显示图片的http链接
      urls: this.data.imageItemVOList.map(item=>item.url) // 需要预览的图片http链接列表
    })
  },
  bindPickerChange(e) {
    const { detail, target } = e
    const { index } = target.dataset
    const { value } = detail
    console.log('picker发送选择改变，携带值为', index, value)
    const tabData = this.data.filterTabs[index].data
    const tabValue = tabData[value]
    console.log(tabValue);
    const filterMap = {
      0:'brandName',
      1:'price',
      2:'typeName',
      3:'sort'
    }
    this.setData({
      filterActive: tabValue.value == 999 ? 999 : index
    })
    const par = {
      ...this.data.listParams,
      [filterMap[index]]:tabValue.value == 999 ? undefined : index == 2 ? tabValue.name :tabValue.value,
    }
    this.getList(par)
    this.setData({
      listParams:{
        ...this.data.listParams,
        ...par
      }
    })
    // district
  },
  bindMultiPickerChange (e) {
    console.log('picker发送选择改变，携带值为', e, e.detail.value)
    const activeAddressName = this.data.addressItemVOS[e.detail.value].addressName
    const district = activeAddressName === '全国' ? '' : activeAddressName
    this.setData({
      activeAddressIndex: e.detail.value,
      activeAddressName
    })
    appData.globalData.currentAddress = district
    setTimeout(() => {
    //  const district = this.getDistrict()
     console.log(district);
      this.getList({
        ...this.data.listParams,
        district,
      })
      this.setData({
        listParams:{
          ...this.data.listParams,
          district,
        }
      })
      // this.setData({
      //   cityName:district,
      //   firstTabActive:district? true : false
      // })
    }, 100);
  },
  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    if(e.detail.column ==2){
      return      
    }
    const provinceIndex = e.detail.column === 0 ? e.detail.value : this.data.multiIndex[0]
    const cityIndex = e.detail.column === 1 ? e.detail.value : this.data.multiIndex[1]
    this.setData({
      multiArray: this.processFilter(this.data.addressItemVOS, provinceIndex, cityIndex)
    })
  },
  bindKeyInput: function (e) {
    this.setData({
      searchVal: e.detail.value
    })
  },
  onSearch(){
    const par = {
      ...this.data.listParams,
      keyword:this.data.searchVal || undefined,
    }
    
    this.getList(par)
  },

})
